<template>
  <div class="box">
    <div class="selectBox">
      <div class="select">
        <div class="select-left">
          <ul>
            <li
              v-if="
                collect.source.selectType == 2 || collect.source.selectType == 3
              "
            >
              <span>源库：</span>
              <el-select
                v-model="data.sourceDatabase"
                placeholder="请选择源库"
                size="small"
                style="width: 70%"
              >
                <el-option
                  v-for="dict in collect.source.nodeTypeOptions"
                  :key="dict.value + Math.random()"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </li>
            <li
              v-if="
                collect.source.selectType == 1 || collect.source.selectType == 3
              "
            >
              <span>源schema：</span>
              <el-select
                v-model="data.sourceDataSchema"
                placeholder="请选择源库"
                size="small"
                style="width: 75%"
              >
                <el-option
                  v-for="dict in collect.source.selectType == 1
                    ? collect.source.nodeTypeOptions
                    : collect.source.schemaSelectData"
                  :key="dict.value + Math.random()"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </li>
          </ul>
        </div>
        <div class="select-right">
          <ul>
            <li
              v-if="
                collect.sink.selectType == 2 || collect.sink.selectType == 3
              "
            >
              <span>目标库：</span>
              <el-select
                v-model="data.sinkDatabase"
                placeholder="请选择目标库"
                size="small"
                style="width: 70%"
              >
                <el-option
                  v-for="dict in collect.sink.nodeTypeOptions"
                  :key="dict.value + Math.random()"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </li>
            <li
              v-if="
                collect.sink.selectType == 1 || collect.sink.selectType == 3
              "
            >
              <span>目标schema：</span>
              <el-select
                v-model="data.sinkDataSchema"
                placeholder="请选择目标schema"
                size="small"
                style="width: 70%"
              >
                <el-option
                  v-for="dict in collect.sink.selectType == 1
                    ? collect.sink.nodeTypeOptions
                    : collect.sink.schemaSelectData"
                  :key="dict.value + Math.random()"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </li>
          </ul>
        </div>
      </div>
    </div>
    <div class="queryBtn">
      <el-button
        type="primary"
        size="small"
        style="width: 80px"
        @click.prevent="handleQuery"
        >查询</el-button
      >
    </div>

    <el-table :data="tableData" border :height="400" v-loading="loading">
      <template slot="empty">
        <el-empty :image-size="100" description="暂无数据"></el-empty>
      </template>
      <el-table-column prop="sourceName" label="源实例名"></el-table-column>
      <el-table-column prop="sinkName" label="目标实例名"></el-table-column>
      <el-table-column prop="sourceTable" label="源表"></el-table-column>
      <el-table-column prop="sinkTable" label="目标表"></el-table-column>
      <el-table-column prop="id" label="主键id" />
      <el-table-column prop="time" label="时间字段" />
    </el-table>
  </div>
</template>

<script>
import {
  databaseListData,
  databaseListTables,
  databaseListDatabaseAndSchema,
} from "@/api/console/datasourceInfo";
import Vue from "vue";

export default {
  name: "HelloWorld3",
  props: ["data"],
  data() {
    return {
      tableData: [],
      form: {
        sourceDatabase: "",
        sinkDatabase: "",
        taskTables: [],
      },
      datasourceInfoList1: [],
      datasourceInfoList2: [],
      rules: {
        sourceName: [
          { required: true, message: "请选择源库", trigger: "change" },
        ],
        sinkName: [
          { required: true, message: "请选择目标库", trigger: "change" },
        ],
      },
      loading: false,
      collect: {
        source: {
          nodeTypeOptions: [],
          schemaSelectData: [],
          selectType: 0,
        },
        sink: {
          nodeTypeOptions: [],
          schemaSelectData: [],
          selectType: 0,
        },
      },
    };
  },
  created() {
    this.gainBaseSelect();
  },
  mounted() {},
  methods: {
    async gainBaseSelect() {
      const {
        start,
        end,
        sourceDatabase,
        sinkDatabase,
        sourceId,
        sinkId,
        sourceDataSchema,
        sinkDataSchema,
      } = this.$props.data;

      this.loading = true;

      let res = await this.getDicts("datasource_database_type");
      res.data.forEach((f) => {
        if (start === f.dictLabel || end === f.dictLabel) {
          this.collect[start === f.dictLabel ? "source" : "sink"].selectType =
            Number(f.dictValue);
        }
      });

      const [sourceRes, sinkRes] = await Promise.all([
        databaseListDatabaseAndSchema({ id: sourceId }),
        databaseListDatabaseAndSchema({ id: sinkId }),
      ]);

      this.changeLibraryData(
        sourceRes.data.data,
        this.collect.source.nodeTypeOptions,
        this.collect.source.schemaSelectData
      );
      this.changeLibraryData(
        sinkRes.data.data,
        this.collect.sink.nodeTypeOptions,
        this.collect.sink.schemaSelectData
      );
      // 更新源数据库和模式
      this.updateDatabaseAndSchema(
        sourceRes.data.data,
        "sourceDatabase",
        "sourceDataSchema",
        this.collect.source.selectType,
        true
      );
      // 更新目标数据库和模式
      this.updateDatabaseAndSchema(
        sinkRes.data.data,
        "sinkDatabase",
        "sinkDataSchema",
        this.collect.sink.selectType,
        false
      );

      this.gainTable();
    },
    updateDatabaseAndSchema(data, dbKey, schemaKey, selectType, isSource) {
      if (!this.$props.data[dbKey] && selectType !== 1) {
        Vue.set(this.$props.data, dbKey, data[0].database);
      }
      if (!this.$props.data[schemaKey] && selectType !== 2) {
        if (selectType === 1) {
          Vue.set(this.$props.data, schemaKey, data[0].database);
        } else {
          Vue.set(this.$props.data, schemaKey, data[0].schemas[0]);
        }
      }
    },
    changeLibraryData(data, value, schemas) {
      if (!data) return;
      const addUnique = (arr, item) => {
        if (!arr.some((existing) => existing.value === item.value)) {
          arr.push(item);
        }
      };
      data.forEach((f) => {
        addUnique(value, { label: f.database, value: f.database });

        if (f.schemas) {
          f.schemas.forEach((v) => {
            addUnique(schemas, { label: v, value: v });
          });
        }
      });
    },
    mapData(data) {
      return data.map((db) => ({
        label: db,
        value: db,
      }));
    },
    // 搜索按钮
    handleQuery() {
      if (
        this.$props.data.sourceDatabase == "" ||
        this.$props.data.sinkDatabase == ""
      ) {
        return this.$message.warning("请选择源库或者目标库");
      }
      this.gainTable();
    },
    async gainTable() {
      this.tableData = [];
      this.loading = true;
      let {
        sourceDatabase,
        sourceDataSchema,
        sinkDatabase,
        sinkDataSchema,
        sourceId,
        sinkId,
        taskTables,
      } = this.$props.data;
      const sourceTable = await databaseListTables({
        databaseName: sourceDatabase || "",
        schemaName: sourceDataSchema || "",
        id: sourceId,
      });
      const sinkTable = await databaseListTables({
        databaseName: sinkDatabase || "",
        schemaName: sinkDataSchema || "",
        id: sinkId,
      });
      this.$props.data.taskTables = sourceTable.data.data;
      const sourceTableSet = new Set(sourceTable.data.data);
      const sinkTableSet = new Set(sinkTable.data.data);
      const combinedTables = [...sourceTableSet, ...sinkTableSet];
      combinedTables.forEach((tableName) => {
        const isSourcePresent = sourceTableSet.has(tableName);
        const isSinkPresent = sinkTableSet.has(tableName);
        this.tableData.push({
          sourceName: sourceDataSchema || sourceDatabase,
          sinkName: sinkDataSchema || sinkDatabase,
          sourceTable: isSourcePresent ? tableName : "-",
          sinkTable: isSinkPresent ? tableName : "-",
        });
      });
      this.$props.data.displayTable = this.tableData;
      this.loading = false;
    },
    handleSelectionChange(selection) {},
    prev() {
      this.$emit("clickPrev");
    },
    clickNext() {
      this.$store.commit("getData", {
        sourceDatabase: this.form.sourceDatabase,
        sinkDatabase: this.form.sinkDatabase,
        taskTables: this.form.taskTables,
      });
      this.$emit("clickNext");
    },
  },
};
</script>

<style scoped lang="scss">
.box {
  margin-top: 40px;
  width: 100%;
  margin: 30px auto;
  border: 1px solid #dcdfe6;
  border-radius: 5px;
  padding: 30px 40px;
}

.selectBox {
  .select {
    display: flex;
    width: 100%;
    span {
      color: #555;
      font-size: 14px;
    }
    .select-left {
      width: 50%;
    }

    .select-right,
    .select-left {
      width: 50%;
      padding-right: 15px;
    }

    ul {
      margin: 0;
      list-style-type: none;
      padding: 0;
      li {
        margin-top: 20px;
        padding: 0;
        width: 100%;
        height: 100%;

        span {
          display: inline-block;
          width: 100px;
        }
      }
    }
  }
}

.queryBtn {
  text-align: right;
  margin: 20px auto;
  width: 90%;
}
</style>
